{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Reverse Nodes in k-Group"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Hard"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #recursion #linked-list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #递归 #链表"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: reverseKGroup"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #K 个一组翻转链表"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>给你链表的头节点 <code>head</code> ，每&nbsp;<code>k</code><em>&nbsp;</em>个节点一组进行翻转，请你返回修改后的链表。</p>\n",
    "\n",
    "<p><code>k</code> 是一个正整数，它的值小于或等于链表的长度。如果节点总数不是&nbsp;<code>k</code><em>&nbsp;</em>的整数倍，那么请将最后剩余的节点保持原有顺序。</p>\n",
    "\n",
    "<p>你不能只是单纯的改变节点内部的值，而是需要实际进行节点交换。</p>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg\" style=\"width: 542px; height: 222px;\" />\n",
    "<pre>\n",
    "<strong>输入：</strong>head = [1,2,3,4,5], k = 2\n",
    "<strong>输出：</strong>[2,1,4,3,5]\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg\" style=\"width: 542px; height: 222px;\" /></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>head = [1,2,3,4,5], k = 3\n",
    "<strong>输出：</strong>[3,2,1,4,5]\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "<strong>提示：</strong>\n",
    "\n",
    "<ul>\n",
    "\t<li>链表中的节点数目为 <code>n</code></li>\n",
    "\t<li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li>\n",
    "\t<li><code>0 &lt;= Node.val &lt;= 1000</code></li>\n",
    "</ul>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>进阶：</strong>你可以设计一个只用 <code>O(1)</code> 额外内存空间的算法解决此问题吗？</p>\n",
    "\n",
    "<ul>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [reverse-nodes-in-k-group](https://leetcode.cn/problems/reverse-nodes-in-k-group/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [reverse-nodes-in-k-group](https://leetcode.cn/problems/reverse-nodes-in-k-group/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['[1,2,3,4,5]\\n2', '[1,2,3,4,5]\\n3']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverse(self, head, end):\n",
    "        pre = None \n",
    "        cur = nxt = head\n",
    "        while cur != end:\n",
    "            nxt = cur.next\n",
    "            cur.next = pre\n",
    "            pre = cur\n",
    "            cur = nxt \n",
    "        return pre\n",
    "    \n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        p1 = p2 = head\n",
    "        for i in range(k):\n",
    "            if not p2: return head\n",
    "            p2 = p2.next\n",
    "        newHead = self.reverse(p1, p2)\n",
    "        p1.next = self.reverseKGroup(p2, k)\n",
    "        return newHead"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode(object):\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution(object):\n",
    "    def reverseKGroup(self, head, k):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :type k: int\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        def getk(head, k):\n",
    "            n, cnt = head, 0\n",
    "            while n and cnt < k - 1:\n",
    "                n = n.next\n",
    "                cnt += 1\n",
    "            if n:\n",
    "                newhead = n.next\n",
    "                n.next = None\n",
    "                cnt += 1\n",
    "            else:\n",
    "                newhead = None\n",
    "            return newhead, cnt\n",
    "        dummy = ListNode(0)\n",
    "        cur = dummy\n",
    "        while head:\n",
    "            seg = head\n",
    "            head, cnt = getk(head, k)\n",
    "            if cnt < k:\n",
    "                cur.next = seg\n",
    "                return dummy.next\n",
    "            else:\n",
    "                n = seg\n",
    "                while n:\n",
    "                    oldnext = cur.next\n",
    "                    cur.next = n\n",
    "                    n = n.next\n",
    "                    cur.next.next = oldnext\n",
    "                cur = seg\n",
    "        return dummy.next\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def transList2Dic(self, head):\n",
    "        cur = head\n",
    "        i = int(0)\n",
    "        d = {}\n",
    "        while cur is not None:\n",
    "            d[i] = cur\n",
    "            i += 1\n",
    "            cur = cur.next\n",
    "        return d\n",
    "    def reverseKGroup(self, head: 'ListNode', k: 'int') -> 'ListNode':\n",
    "        d = self.transList2Dic(head)\n",
    "        node_num = len(d)\n",
    "        loop_num = int(node_num/k)\n",
    "        last_num = node_num % k\n",
    "        for i in range(loop_num):\n",
    "            if i < loop_num - 1:\n",
    "                d[i*k].next = d[(i + 2) * k - 1]\n",
    "                for j in range(1, k):\n",
    "                    d[i*k+j].next = d[i*k+j-1]\n",
    "            elif i == loop_num - 1:\n",
    "                if last_num == 0:\n",
    "                    d[i * k].next = None\n",
    "                else:\n",
    "                    d[i*k].next = d[(i + 1) * k]\n",
    "                for j in range(1, k):\n",
    "                    d[i*k+j].next = d[i*k+j-1]\n",
    "            else:\n",
    "                if last_num == 0:\n",
    "                    d[i * k].next = None\n",
    "                    for j in range(1, k):\n",
    "                        d[i * k + j].next = d[i * k + j - 1]\n",
    "        if loop_num == 0:\n",
    "            return head\n",
    "        return d[k-1]\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head, k):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :type k: int\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        reHead = ListNode(0)\n",
    "        preHead = reHead\n",
    "        preHead.next,cursor = head,head\n",
    "        queue = []\n",
    "        \n",
    "        while cursor:\n",
    "             queue.append(cursor)\n",
    "             cursor = cursor.next\n",
    "             if len(queue)==k:\n",
    "                 while queue:\n",
    "                     preHead.next = queue.pop()\n",
    "                     preHead = preHead.next\n",
    "        while queue:\n",
    "            preHead.next = queue.pop(0)\n",
    "            preHead = preHead.next\n",
    "        preHead.next = None\n",
    "        return reHead.next\n",
    "       \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "   def reverseKGroup(self, head, k):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :type k: int\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        new_head = ListNode(-1)\n",
    "        tmp_values = []\n",
    "        pointer = head\n",
    "        new_pointer = new_head\n",
    "        while pointer is not None:\n",
    "            tmp_values.append(pointer.val)\n",
    "            if len(tmp_values) == k:\n",
    "                for value in reversed(tmp_values):\n",
    "                    new_pointer.next = ListNode(value)\n",
    "                    new_pointer = new_pointer.next\n",
    "                tmp_values = []\n",
    "            pointer = pointer.next\n",
    "        if len(tmp_values) != 0:\n",
    "            for value in tmp_values:\n",
    "                new_pointer.next = ListNode(value)\n",
    "                new_pointer = new_pointer.next\n",
    "        return new_head.next\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: 'ListNode', k: 'int') -> 'ListNode':\n",
    "        start=ListNode(0)\n",
    "        st=ListNode(0)\n",
    "        st=start\n",
    "        if head==None:\n",
    "            return None\n",
    "        p=head.next\n",
    "        g=head\n",
    "        i=0\n",
    "        while head!=None:\n",
    "            i=0\n",
    "            g=head\n",
    "            while g!=None:\n",
    "                i+=1\n",
    "                g=g.next\n",
    "                if i>=k:\n",
    "                    break\n",
    "            if i<k:\n",
    "                start.next=head\n",
    "                return st.next\n",
    "            for i in range(k):\n",
    "                print(head.val)\n",
    "                head.next=start.next\n",
    "                start.next=head\n",
    "                head=p\n",
    "                if p!=None:\n",
    "                    p=p.next\n",
    "            print('sadw')\n",
    "            if head==None:\n",
    "                return st.next\n",
    "            for i in range(k):\n",
    "                start=start.next\n",
    "                print(start.val)\n",
    "            print('sadw')\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head, k):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :type k: int\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        original = self.ntl(head)\n",
    "        new=[]\n",
    "        mod_num = len(original)%k\n",
    "        if mod_num == 0:\n",
    "            for i in range(len(original)//k):\n",
    "                for j in range(k):\n",
    "                    new.append(original[i*k+k-j-1])\n",
    "        elif mod_num != 0:\n",
    "            for i in range((len(original)-mod_num)//k):\n",
    "                for j in range(k):\n",
    "                    new.append(original[i*k+k-j-1])\n",
    "        print(new)\n",
    "        for i in range(mod_num):\n",
    "            new.append(original[i-mod_num])\n",
    "        for i in range(len(new)-1):\n",
    "            new[i].next = new[i+1]\n",
    "        if len(new)>0:\n",
    "            new[-1].next = None\n",
    "        \n",
    "        if len(original)>1:\n",
    "            return new[0]\n",
    "        else:return head\n",
    "    \n",
    "    def ntl(self,head):\n",
    "        ret =[]\n",
    "        next_node = head\n",
    "        while 1:\n",
    "            if next_node != None:\n",
    "                ret.append(next_node)\n",
    "                \n",
    "            else:\n",
    "                break\n",
    "            next_node = next_node.next\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head, k):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :type k: int\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        if not head: return head\n",
    "        if k < 2: return head\n",
    "        nodes = []\n",
    "        cur = head\n",
    "        \n",
    "        while cur:\n",
    "            nodes.append(cur.val)\n",
    "            cur = cur.next\n",
    "        \n",
    "        if len(nodes) < k : return head\n",
    "        \n",
    "        groups = len(nodes)//k\n",
    "        \n",
    "        for i in range(k//2):\n",
    "            for j in range(groups):\n",
    "                cc = j * k\n",
    "                print(i, j, cc, cc+i, cc+k-i-1)\n",
    "                nodes[cc + i], nodes[cc + k-i-1] = nodes[cc + k-i-1] , nodes[cc + i]\n",
    "        \n",
    "        cur = head\n",
    "        \n",
    "        for i in nodes:\n",
    "            cur.val = i\n",
    "            cur = cur.next\n",
    "        \n",
    "        return head\n",
    "        \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        p=ListNode(-1)\n",
    "        cur=p\n",
    "        while True:\n",
    "            stack=[]\n",
    "            temp=head\n",
    "            count=k\n",
    "            while count and temp:\n",
    "                count-=1\n",
    "                stack.append(temp)\n",
    "                temp=temp.next\n",
    "            if count:\n",
    "                cur.next=head\n",
    "                break\n",
    "            while stack:\n",
    "                cur.next=stack.pop()\n",
    "                cur=cur.next\n",
    "            cur.next=temp\n",
    "            head=temp\n",
    "        return p.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        dummy = ListNode(0)\n",
    "        p = dummy\n",
    "        length = 0\n",
    "        pre_head = head;\n",
    "        while pre_head:\n",
    "            length = length+1\n",
    "            pre_head = pre_head.next\n",
    "        if length < k:\n",
    "            return head\n",
    "        while True:\n",
    "            stack =[]\n",
    "            count = k\n",
    "            tmp = head\n",
    "            #一轮逆序，将k个值压栈\n",
    "            while count and tmp:\n",
    "                stack.append(tmp)\n",
    "                tmp = tmp.next\n",
    "                count = count - 1\n",
    "            #最后一次无法完成逆序（剩余元素<k），将剩余的head粘到p后面\n",
    "            if count:\n",
    "                p.next = head\n",
    "                break\n",
    "            while stack:\n",
    "                p.next = stack.pop()\n",
    "                p = p.next\n",
    "            #将一个k周期的链表逆序后将后面的链表粘到后面\n",
    "            p.next = tmp\n",
    "            #将tmp后面的链表重新赋值给head让其进行新一轮的逆序\n",
    "            head = tmp\n",
    "        #print(printlinklist(dummy.next))\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        dummy = ListNode(0)\n",
    "        p = dummy\n",
    "        while True:\n",
    "            count = k \n",
    "            stack = []\n",
    "            tmp = head\n",
    "            while count and tmp:\n",
    "                stack.append(tmp)\n",
    "                tmp = tmp.next\n",
    "                count -= 1\n",
    "            # 注意,目前tmp所在k+1位置\n",
    "            # 说明剩下的链表不够k个,跳出循环\n",
    "            if count : \n",
    "                p.next = head\n",
    "                break\n",
    "            # 翻转操作\n",
    "            while stack:\n",
    "                p.next = stack.pop()\n",
    "                p = p.next\n",
    "            #与剩下链表连接起来 \n",
    "            p.next = tmp\n",
    "            head = tmp\n",
    "        \n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        cur=newHead=ListNode('')\n",
    "        p=newHead.next=head\n",
    "        stack=[]\n",
    "        while True:\n",
    "            for i in range(k):\n",
    "                if p:\n",
    "                    stack.append(p)\n",
    "                    p = p.next\n",
    "                else:\n",
    "                    return newHead.next\n",
    "            while stack:\n",
    "                cur.next=stack.pop()\n",
    "                cur=cur.next\n",
    "                cur.next=p\n",
    "        return newHead.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        dummy = ListNode(-1)\n",
    "        dummy.next = head\n",
    "        pre = dummy\n",
    "        end = dummy\n",
    "        while end.next:\n",
    "            for i in range(k):\n",
    "                if not end:\n",
    "                    break\n",
    "                end = end.next\n",
    "            if not end:\n",
    "                break\n",
    "            start = pre.next\n",
    "            ne = end.next\n",
    "            end.next = None\n",
    "            pre.next = self.reverse(start)\n",
    "            start.next = ne\n",
    "            pre = start\n",
    "            end = start\n",
    "        return dummy.next\n",
    "\n",
    "\n",
    "    def reverse(self, head):\n",
    "        if not head: return None\n",
    "        cur = head\n",
    "        pre = None\n",
    "        while cur:\n",
    "            temp = cur.next\n",
    "            cur.next = pre\n",
    "            pre = cur\n",
    "            cur = temp\n",
    "        return pre"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "            p = head\n",
    "            count = 0\n",
    "            while head:\n",
    "                count += 1\n",
    "                head = head.next\n",
    "            n = count//k\n",
    "            headnode = tail = curhead = ListNode(0)\n",
    "            for i in range(n):\n",
    "                curhead = tail\n",
    "                tmp = p\n",
    "                for _ in range(k):\n",
    "                    r = p.next\n",
    "                    p.next = curhead.next\n",
    "                    curhead.next = p\n",
    "                    p = r\n",
    "                tail.next = curhead.next\n",
    "                tail = tmp\n",
    "            tail.next = p\n",
    "            return headnode.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        # 是两个一组反转链表的一般情况\n",
    "        if not head: return head\n",
    "        dummy_node = ListNode(-1)\n",
    "        dummy_node.next = head\n",
    "        pre = dummy_node\n",
    "        cur = head\n",
    "        while True:\n",
    "            count = 0\n",
    "            while count < k and cur:\n",
    "                cur = cur.next\n",
    "                count += 1\n",
    "            if count < k:\n",
    "                return dummy_node.next\n",
    "            p1, p2 = pre.next, cur\n",
    "            old_tail = pre.next\n",
    "            for _ in range(k):\n",
    "                # print(p1, p2)\n",
    "                p1.next, p1, p2 = p2, p1.next, p1\n",
    "            pre.next = p2\n",
    "            pre = old_tail\n",
    "        return dummy_node.next\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        def reverse(head):\n",
    "            cur = head\n",
    "            pre = None\n",
    "            while cur:\n",
    "                cur.next, cur, pre = pre, cur.next, cur\n",
    "            return pre\n",
    "\n",
    "        dummy = ListNode(-1)\n",
    "        dummy.next = head\n",
    "\n",
    "        pre = dummy\n",
    "        end = dummy\n",
    "\n",
    "        while end:\n",
    "            for _ in range(k):\n",
    "                if end:\n",
    "                    end = end.next\n",
    "            if not end:\n",
    "                break\n",
    "                \n",
    "            next_group = end.next\n",
    "            end.next = None\n",
    "\n",
    "            start = pre.next\n",
    "            pre.next = reverse(start)\n",
    "\n",
    "            start.next = next_group\n",
    "\n",
    "            pre = start\n",
    "            end = start\n",
    "\n",
    "        return dummy.next\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        node = head\n",
    "        count = k\n",
    "        while count > 0:\n",
    "            if not node:\n",
    "                return head\n",
    "            node = node.next\n",
    "            count -= 1\n",
    "        cur_1 = node\n",
    "        node = head\n",
    "        prev = None\n",
    "        while node != cur_1:\n",
    "            temp = node.next\n",
    "            node.next = prev\n",
    "            prev = node\n",
    "            node = temp\n",
    "        head.next = self.reverseKGroup(node, k)\n",
    "        return prev\n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "class ListNode:\n",
    "    def __init__(self, val=0, next=None):\n",
    "        self.val = val\n",
    "        self.next = next\n",
    "class Solution:\n",
    "    #翻转子链表，并且返回新的头和尾\n",
    "    def reverse(self,head,tail):\n",
    "        prev=tail.next\n",
    "        p=head\n",
    "        while prev !=tail:\n",
    "            nex=p.next\n",
    "            p.next=prev\n",
    "            prev=p\n",
    "            p=nex\n",
    "        return tail,head\n",
    "\n",
    "    def reverseKGroup(self, head, k):\n",
    "        hair=ListNode(0)\n",
    "        hair.next=head\n",
    "        pre=hair\n",
    "\n",
    "        while head:\n",
    "            tail=pre\n",
    "            #查看剩余部分长度是否大于等于k\n",
    "            for i in range(k):\n",
    "                tail= tail.next\n",
    "                if not tail:\n",
    "                    return hair.next\n",
    "            nex=tail.next\n",
    "            head,tail=self.reverse(head,tail)\n",
    "            #把子链表重新接回原链表\n",
    "            pre.next=head\n",
    "            tail.next=nex\n",
    "            pre=tail\n",
    "            head=tail.next\n",
    "        return hair.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        l = []\n",
    "        while head:\n",
    "            l.append(head.val)\n",
    "            head = head.next\n",
    "        length = len(l)\n",
    "        out = []\n",
    "        last_i = 0\n",
    "        i = k\n",
    "        while True:\n",
    "            temp = l[last_i:i][::-1]\n",
    "            out += temp\n",
    "            last_i = i\n",
    "            i += k\n",
    "            if i > length:\n",
    "                break\n",
    "        out += l[last_i:i]\n",
    "        \n",
    "            \n",
    "        node = ListNode(0)\n",
    "        move = node\n",
    "        for v in out:\n",
    "            move.next = ListNode(v)\n",
    "            move = move.next\n",
    "        return node.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "\n",
    "        if not head or not head.next:\n",
    "            return head\n",
    "\n",
    "        begin, end = head, head\n",
    "        for i in range(k):\n",
    "\n",
    "            if not end:\n",
    "                return begin\n",
    "            end = end.next\n",
    "\n",
    "        newhead = self.reverse(begin, end)\n",
    "\n",
    "        begin.next = self.reverseKGroup(end, k)\n",
    "\n",
    "        return newhead\n",
    "\n",
    "    def reverse(self, begin: ListNode, end: ListNode) -> ListNode:\n",
    "\n",
    "        pre, cur = None, begin\n",
    "\n",
    "        while cur != end:\n",
    "            nxt = cur.next\n",
    "            cur.next = pre\n",
    "            pre = cur\n",
    "            cur = nxt\n",
    "\n",
    "        return pre\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        dummy=ListNode()\n",
    "        pre=dummy\n",
    "        pre.next=head\n",
    "        cur=head\n",
    "        n=0\n",
    "        while cur:\n",
    "            n+=1\n",
    "            cur=cur.next\n",
    "        cur=head\n",
    "        num=n//k\n",
    "        while num:\n",
    "            c=k-1\n",
    "            while c: \n",
    "                nex=cur.next\n",
    "                cur.next=nex.next\n",
    "                nex.next=pre.next\n",
    "                pre.next=nex\n",
    "                c-=1\n",
    "            pre=cur\n",
    "            cur=pre.next\n",
    "            num-=1\n",
    "        return dummy.next\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        def getKth(curr, k):\n",
    "            while curr and k>0:\n",
    "                curr = curr.next\n",
    "                k -=1\n",
    "            return curr\n",
    "        dummy = ListNode(0,head)\n",
    "        groupPrev= dummy\n",
    "        while True:\n",
    "            kth = getKth(groupPrev, k)\n",
    "            if not kth:\n",
    "                break\n",
    "            groupNxt = kth.next\n",
    "            prev , curr = groupNxt, groupPrev.next\n",
    "            while curr!=groupNxt:\n",
    "                curr.next, curr, prev = prev, curr.next, curr\n",
    "        \n",
    "            groupPrev.next, groupPrev = kth, groupPrev.next\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        n = 0\n",
    "        cur = head\n",
    "        while cur:\n",
    "            n += 1\n",
    "            cur = cur.next\n",
    "        \n",
    "        dummy = ListNode(next=head)\n",
    "        p0 = dummy\n",
    "        pre = None\n",
    "        cur = p0.next\n",
    "\n",
    "        while n >= k:\n",
    "            n -= k\n",
    "            for _ in range(k):\n",
    "                nxt = cur.next\n",
    "                cur.next = pre\n",
    "                pre = cur\n",
    "                cur = nxt\n",
    "            nxt = p0.next\n",
    "            p0.next.next = cur\n",
    "            p0.next = pre\n",
    "            p0 = nxt\n",
    "        return dummy.next\n",
    "        \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        n = 0\n",
    "        cur = head\n",
    "        while cur:\n",
    "            n += 1\n",
    "            cur = cur.next\n",
    "        \n",
    "        dummy = ListNode(next=head)\n",
    "        p0 = dummy\n",
    "        pre = None\n",
    "        cur = p0.next\n",
    "\n",
    "        while n >= k:\n",
    "            n -= k\n",
    "            for _ in range(k):\n",
    "                nxt = cur.next\n",
    "                cur.next = pre\n",
    "                pre = cur\n",
    "                cur = nxt\n",
    "            nxt = p0.next\n",
    "            p0.next.next = cur\n",
    "            p0.next = pre\n",
    "            p0 = nxt\n",
    "        return dummy.next\n",
    "        \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverse(self,head: ListNode,tail: ListNode):\n",
    "        pre = tail.next\n",
    "        p = head\n",
    "        while pre!=tail:\n",
    "            nex = p.next\n",
    "            p.next = pre\n",
    "            pre = p\n",
    "            p = nex\n",
    "        return tail,head\n",
    "\n",
    "\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        hair = ListNode(0)\n",
    "        hair.next = head\n",
    "        pre = hair\n",
    "        while head:\n",
    "            tail = pre\n",
    "            for i in range(k):\n",
    "                tail = tail.next\n",
    "                if not tail:\n",
    "                    return hair.next\n",
    "            nex = tail.next\n",
    "            head,tail = self.reverse(head, tail)\n",
    "            pre.next = head\n",
    "            tail.next = nex\n",
    "            pre = tail\n",
    "            head = tail.next\n",
    "        return hair.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        res = []\n",
    "        while head:\n",
    "            res.append(head.val)\n",
    "            head = head.next\n",
    "        for epoch in range(len(res)//k):\n",
    "            res[k*epoch:k*(epoch+1)] = res[k*epoch:k*(epoch+1)][::-1]\n",
    "        dummy = ListNode()\n",
    "        start = dummy\n",
    "        for num in res:\n",
    "            dummy.next = ListNode(num)\n",
    "            dummy = dummy.next\n",
    "        return start.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        if k == 1:\n",
    "            return head\n",
    "        pre = dum = ListNode(-1)\n",
    "        dum.next = head\n",
    "        count = 1\n",
    "        start_node = pre.next\n",
    "        def reverse(new_head: Optional[ListNode]):\n",
    "            pre_ = None\n",
    "            cur = new_head\n",
    "            while cur:\n",
    "                next = cur.next\n",
    "                cur.next = pre_\n",
    "                pre_ = cur\n",
    "                cur = next\n",
    "\n",
    "\n",
    "        while head:\n",
    "            if count % k == 0:\n",
    "                end_node = head\n",
    "                head = head.next\n",
    "                end_node.next = None\n",
    "                pre.next = None\n",
    "                reverse(start_node)\n",
    "                pre.next = end_node\n",
    "                start_node.next = head\n",
    "                pre = start_node\n",
    "                start_node = head\n",
    "                count = 1\n",
    "            else:\n",
    "                head = head.next\n",
    "                count += 1\n",
    "        if head != start_node:\n",
    "            pre.next = start_node\n",
    "        return dum.next\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        n = 0\n",
    "        cur = head\n",
    "        while cur:\n",
    "            n += 1\n",
    "            cur = cur.next\n",
    "        \n",
    "        dum = ListNode(-1)\n",
    "        dum.next = head\n",
    "\n",
    "        p0 = dum\n",
    "        while n >= k:\n",
    "            n -= k \n",
    "\n",
    "            pre = None\n",
    "            cur = p0.next\n",
    "            for _ in range(k):\n",
    "                next = cur.next\n",
    "                cur.next = pre\n",
    "                pre = cur\n",
    "                cur = next\n",
    "\n",
    "            nxt = p0.next\n",
    "            p0.next.next = cur\n",
    "            p0.next = pre\n",
    "            p0 = nxt\n",
    "        return dum.next\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    # 翻转一个子链表，并且返回新的头与尾\n",
    "    def reverse(self, head: ListNode, tail: ListNode):\n",
    "        prev = tail.next\n",
    "        p = head\n",
    "        while prev != tail:\n",
    "            nex = p.next\n",
    "            p.next = prev\n",
    "            prev = p\n",
    "            p = nex\n",
    "        return tail, head\n",
    "\n",
    "    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n",
    "        hair = ListNode(0)\n",
    "        hair.next = head\n",
    "        pre = hair\n",
    "\n",
    "        while head:\n",
    "            tail = pre\n",
    "            # 查看剩余部分长度是否大于等于 k\n",
    "            for i in range(k):\n",
    "                tail = tail.next\n",
    "                if not tail:\n",
    "                    return hair.next\n",
    "            nex = tail.next\n",
    "            head, tail = self.reverse(head, tail)\n",
    "            # 把子链表重新接回原链表\n",
    "            pre.next = head\n",
    "            tail.next = nex\n",
    "            pre = tail\n",
    "            head = tail.next\n",
    "        \n",
    "        return hair.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        \n",
    "        \n",
    "        def reverse(h):\n",
    "            ans=ListNode()\n",
    "            ans.next=h\n",
    "\n",
    "            end=h\n",
    "            \n",
    "            temp=ans\n",
    "\n",
    "            now=h.next   \n",
    "            while now:\n",
    "                \n",
    "                \n",
    "                new=now\n",
    "                now=now.next\n",
    "                \n",
    "                old=ans.next \n",
    "              \n",
    "                new.next=old\n",
    "                \n",
    "                ans.next=new\n",
    "                \n",
    "                if h==None:\n",
    "                    break\n",
    "            end.next=None\n",
    "            return ans.next,end\n",
    "        \n",
    "        \n",
    "        if k==1:\n",
    "            return head\n",
    "        \n",
    "        res=ListNode()\n",
    "        temp=res\n",
    "        point=head\n",
    "        \n",
    "        # 1 2 3 4 5 6\n",
    "       \n",
    "        sum=0\n",
    "        while(head):\n",
    "            sum+=1\n",
    "            \n",
    "            if(sum==1):\n",
    "                point=head\n",
    "            \n",
    "            if sum ==k:\n",
    "                \n",
    "                sum=0\n",
    "                \n",
    "                temp_head=head.next\n",
    "                head.next=None\n",
    "                a,b=reverse(point)  #\n",
    "                b.next=temp_head   ##将后续的接到最当前目标的后面\n",
    "                temp.next=a\n",
    "                temp=b\n",
    "                head=b\n",
    "            \n",
    "            \n",
    "           \n",
    "            head=head.next\n",
    "        if sum!=0:\n",
    "            temp.next=point\n",
    "        return res.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n",
    "        lst=[]\n",
    "        while head:\n",
    "            lst.append(head.val)\n",
    "            head=head.next\n",
    "        l=len(lst)\n",
    "        slst=[]\n",
    "        if len(lst)<k:\n",
    "            slst=lst\n",
    "        else:\n",
    "            for i in range(len(lst)//k):\n",
    "                slst+=lst[i*k:(i+1)*k][::-1]\n",
    "        if l%k==0:\n",
    "            slst=slst\n",
    "        elif l%k==1:\n",
    "            slst.append(lst[-1])\n",
    "        else:\n",
    "            slst+=lst[::-1][0:(l%k)][::-1]\n",
    "        if not slst:\n",
    "            return None\n",
    "        else:\n",
    "            lnode=ListNode(slst[0])\n",
    "            lhead=lnode\n",
    "            for i in slst[1:]:\n",
    "                lhead.next=ListNode(i)\n",
    "                lhead=lhead.next\n",
    "            return lnode"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
